package com.sayice.design.util;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;

/**
 * @author shubing
 */
public class XmlParse {
    private static DocumentBuilder docBuilder;
    private final Document doc;
    
    static {
        try {
            docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
    }
    
    public XmlParse(String path) throws IOException, SAXException {
        doc = docBuilder.parse(path);
    }
    
    public String stringOfTag(String tagName) {
        return valueOf(tagName);
    }
    
    public Object objectOfTag(String tagName) {
        String className = valueOf(tagName);
        try {
            Class<?> clazz = Class.forName(className);
            return clazz.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    private String valueOf(String tagName) {
        NodeList list = doc.getElementsByTagName(tagName);
        Node node = list.item(0);
        if (node == null) {
            return null;
        }
        Node firstChild = node.getFirstChild();
        if (firstChild == null) {
            return null;
        }
        String value = firstChild.getNodeValue();
        return value == null ? null : value.trim();
    }
}
